package face;

import java.util.LinkedList;
import java.util.Queue;


/**
 * @author spf
 * @date 2024/5/21
 * @time 16:18
 */

/**
 * 如何用队列实现栈
 * @param <T>
 */
public class QueueToStack<T> {

    private Queue<T> queue;
    private Queue<T> tempQueue;

    public QueueToStack(){
        queue = new LinkedList<>();
        tempQueue = new LinkedList<>();
    }

    public void push(T element){
        queue.offer(element);
    }

    public T pop(){
        if(isEmpty()){
            throw new RuntimeException("Stack is empty");
        }
        while (queue.size() > 1){
            tempQueue.offer(queue.poll());
        }
        T element = queue.poll();
        Queue<T> temp = queue;
        queue = tempQueue;
        tempQueue = temp;
        return element;
    }

    public T peek(){
        if (isEmpty()){
            throw new RuntimeException("Stack is empty");
        }
        while(queue.size() > 1){
            tempQueue.offer(queue.poll());
        }
        T element = queue.poll();
        tempQueue.offer(queue.poll());
        Queue<T> temp = queue;
        queue = tempQueue;
        tempQueue = temp;
        return element;
    }

    private boolean isEmpty() {
        return queue.isEmpty();
    }
}
